import { ref, reactive } from 'vue'
import type { Order } from '@/TS/Hooks/Home/components/Order'
import * as $http from '@/utlis/interface/orderDlatils'
import { runErrandTitleText } from '@/utlis/setStatusText'

interface pickCdoeDta {
	orderId: string | number,
	pickCode: any,
	riderDo: number | null
}
interface routeLine {
	points: Array<{ latitude: string; longitude: string }>
}
interface baseDataShow {
	sendCode: boolean,
	codeTextShow: boolean,
	colorShow: boolean,
	codeText: string,
	titleText: string | null



}
interface covers {
	startingLatitude: number | string | null
	startingLongitude: number | string | null
	terminalLatitude: number | string | null
	terminalLongitude: number | string | null
}
// 电话
export default (proxy: any, orderTypes: any) => {
	// tabs分类默认值
	const Type = ref<number>()
	const confirmChange = () => { }
	//打电话联系商家
	const callPhone = (phone: string, people: string) => {
		if (people == "联系收件人") {
			let peoplePhone = orderObj.receivePhone
			if (peoplePhone) {
				uni.makePhoneCall({
					phoneNumber: peoplePhone,
				})
			}
		} else {
			let peoplePhone = orderObj.pickPhone
			if (peoplePhone) {
				uni.makePhoneCall({
					phoneNumber: peoplePhone,
				})
			}
		}

	}
	let timeData = reactive<Order.timeData>({})
	const onChange = (e: any) => {
		timeData.hours = e.hours >= 10 ? e.hours : '0' + e.hours
		timeData.minutes = e.minutes >= 10 ? e.minutes : '0' + e.minutes
		timeData.seconds = e.seconds >= 10 ? e.seconds : '0' + e.seconds
	}

	//获取当前订单详情
	/*   AddConfigType   订单状态区分
		   0为新任务
		   1为待配送
		   2位待收货
	*/
	let orderObj = reactive<any>({
		orderId: null,
		orderType: null,
		predictTime: null,
		riderDo: null,
		pickAddressDistance: null,
		pickAddress: null,
		pickName: null,
		pickPhone: null,
		receiveAddressDistance: null,
		receiveAddress: null,
		receiveName: null,
		receivePhone: null,
		riderClientStatus: null,
		riderPhone: "",
		articleType: null,
		articlePrice: null,
		articleWeight: null,
		articleNum: null,
		remark: null,
		orderSn: null,
		createTime: null,
		price: null,
		locationVO: null,
		startingLongitude: null,
		startingLatitude: null,
		terminalLongitude: null,
		terminalLatitude: null,
		titleName: null,
		currentStatus: null,
		GoodsTypeShow: true,
		sfBuy: null,
		startTime: null,
		status: null,
	})
	const defaultShow = ref(false)
	//地图路线
	const routeLine = reactive<routeLine>({
		points: [],
	})
	//取货点
	/*startingLongitude	起点经度(商家)
	 startingLongitude	起点经度(商家)
	 terminalLongitude	终点经度(用户)
	 terminalLatitude	终点纬度(用户)
	*/
	const covers = reactive<covers>({
		startingLatitude: '',
		startingLongitude: '',
		terminalLatitude: '',
		terminalLongitude: '',
	})
	// 跑腿订单取货码
	const takeGoodInfo = reactive<pickCdoeDta>({
		orderId: '',
		pickCode: null,
		riderDo: null
	})

	const baseDataShow = reactive<baseDataShow>({
		codeTextShow: false,
		sendCode: false,
		colorShow: false,
		codeText: '请输入正确的取货码',
		titleText: null


	})
	const statusShowType = ref<boolean>(false)
	// 获取订单详情
	const getDelatis = (Type: number, id: number, lng: string | number, lat: string | number) => {
		/**  Type 订单类型 {0,1,2}   0 新任务 1 待取货 2 配送中
		 * orderType 订单状态 {0,1}  0 外卖订单  1  跑腿订单
		 *
		 */
		let data = {
			longitude: lng,
			latitude: lat,
			orderId: id
		}
		//  跑腿新任务详情
		if (Type == 0) {
			$http.runErrandNewTask(data, proxy).then((res: any) => {
				if (res.code == 0) {

					for (let i in orderObj) {
						for (let j in res.data) {
							if (i == j) {
								orderObj[i] = res.data[j]
							}
						}
					}
					res.data.pickAddressDistance == '' ? orderObj.pickAddressDistance = 0 : res.data.pickAddressDistance
					res.data.receiveAddressDistance == '' ? orderObj.receiveAddressDistance = 0 : res.data.receiveAddressDistance


				}
			}).catch((err: any) => {
				proxy.$API(proxy).Toast(err.msg, 'error')
			})
		} else if (Type == 1) {
			//跑腿待取货详情
			$http.runErrandWaitPickItemDelails(data, proxy).then((res: any) => {
				if (res.code == 0) {
					orderObj.BtnSaveTitle = runErrandTitleText(res.data.currentStatus)
					if (res.data.sfBuy == 0) {
						for (let i in orderObj) {
							for (let j in res.data) {
								if (i == j) {
									orderObj[i] = res.data[j]
								}
							}
						}
						covers.startingLongitude = res.data.startingLongitude
						covers.startingLatitude = res.data.startingLatitude
						covers.terminalLongitude = res.data.terminalLongitude
						covers.terminalLatitude = res.data.terminalLatitude
						res.data?.locationVO.locationResultVOs?.forEach((item: any, index: number) => {
							routeLine.points.push(item)
						})
						setTimeout(() => {
							statusShowType.value = true
						}, 500)

					} else {

						for (let i in orderObj) {
							for (let j in res.data) {
								if (i == j) {
									orderObj[i] = res.data[j]
								}
							}
						}
						covers.startingLongitude = res.data.startingLongitude
						covers.startingLatitude = res.data.startingLatitude
						covers.terminalLongitude = res.data.terminalLongitude
						covers.terminalLatitude = res.data.terminalLatitude
						setTimeout(() => {
							statusShowType.value = true
						}, 500)

					}
				}
			}).catch((err: any) => {
				proxy.$API(proxy).Toast(err.msg, 'error')

			})
			//  跑腿配送中详情
		} else if (Type == 2) {
			console.log("**");

			$http.runErrandDistributionDeltails(data, proxy).then((res: any) => {
				if (res.code == 0) {
					setTimeout(() => {
						statusShowType.value = true
					}, 500)
					orderObj.BtnSaveTitle = runErrandTitleText(res.data.currentStatus)
					for (let i in orderObj) {
						for (let j in res.data) {
							if (i == j) {
								orderObj[i] = res.data[j]
							}
						}
					}
					covers.startingLongitude = res.data.startingLongitude
					covers.startingLatitude = res.data.startingLatitude
					covers.terminalLongitude = res.data.terminalLongitude
					covers.terminalLatitude = res.data.terminalLatitude
					res.data.locationVO.locationResultVOs?.forEach((item: any, index: number) => {
						routeLine.points.push(item)
					})

				}
			}).catch((err: any) => {
				proxy.$API(proxy).Toast(err.msg, 'error')
			})
		}
	}
	const butChange = reactive<any>({
		title: '抢单',
		btn_disable: true,
	})
	//抢单
	const makeOrder = (id: number | string) => {
		$http.runErrandsMakeOrder('', id, proxy).then((res: any) => {
			if (res.code == 0) {
				proxy.$API(proxy).Toast(res.msg, 'success')
				setTimeout(() => {
					uni.navigateBack({
						delta: 1

					})
				}, 1000)
			}
		}).catch((err: any) => {
			proxy.$API(proxy).Toast(err.msg, 'error')
		})
	}

	//我已取货 或者确认到店
	const takeGoods = (orderObj: any, listStatus: number | string) => {
		if (orderTypes.statusType == 1) {
			baseDataShow.titleText = '确定取货吗'
		} else {
			baseDataShow.titleText = '确定收货吗'
		}
		console.log(77, orderObj, listStatus);

		switch (listStatus) {
			case 3:
				statusShowType.value = false
				baseDataShow.sendCode = true
				takeGoodInfo.orderId = orderObj.orderId
				break
			case 4:
				statusShowType.value = false
				baseDataShow.sendCode = true
				takeGoodInfo.orderId = orderObj.orderId
				break
			case 5:
				statusShowType.value = false
				baseDataShow.sendCode = true
				takeGoodInfo.orderId = orderObj.orderId
				break
			default:
				let data = {
					orderId: orderObj.orderId,
					pickCode: null,
					riderLongitude: uni.getStorageSync('riderLongitude'),
					riderLatitude: uni.getStorageSync('riderLatitude'),
				}
				orderTypes.statusType == 1 ? baseDataShow.titleText = "取货码" : '收货码'
			// $http.runErrandReceviedGoods(data, proxy).then((res : any) => {
			// 	if (res.code == 0) {
			// 		baseDataShow.sendCode = false
			// 		proxy.$API(proxy).Toast(res.msg, 'success')
			// 		setTimeout(() => {
			// 			uni.navigateBack({ delta: 1 })
			// 		}, 1000);
			// 	}
			// }).catch((err : any) => {
			// 	proxy.$API(proxy).Toast(err.msg, 'error')
			// })

		}
	}
	const cancelSendCode = () => {
		baseDataShow.sendCode = false
		baseDataShow.codeTextShow = false



	}
	const confirmSendCode = () => {


		let data = {
			orderId: takeGoodInfo.orderId,
			pickCode: takeGoodInfo.pickCode,
			riderLongitude: uni.getStorageSync('riderLongitude'),
			riderLatitude: uni.getStorageSync('riderLatitude'),

		}
		//我已取货
		if (orderTypes.statusType == 1) {
			$http.runErrandReceviedGoods(data, Proxy).then((res: any) => {
				if (res.code == 0) {
					statusShowType.value = true
					baseDataShow.sendCode = false
					proxy.$API(proxy).Toast(res.msg, 'success')
					setTimeout(() => {


						uni.navigateBack({
							delta: 1
						})
					}, 1000)
				}
			}).catch((err: any) => {
				baseDataShow.codeText = err.msg
				baseDataShow.codeTextShow = true
			})
			//我已送达
		} else if (orderTypes.statusType == 2) {
			let Data = {
				orderId: takeGoodInfo.orderId,
				receiveCode: takeGoodInfo.pickCode,
				riderLongitude: uni.getStorageSync('riderLongitude'),
				riderLatitude: uni.getStorageSync('riderLatitude'),
			}
			$http.runErrandsdelivered(Data, Proxy).then((res: any) => {
				if (res.code == 0) {
					statusShowType.value = true
					baseDataShow.sendCode = false
					proxy.$API(proxy).Toast(res.msg, 'success')
					setTimeout(() => {
						baseDataShow.codeText = `请输入正确的${baseDataShow.titleText}`
						uni.navigateBack({ delta: 1 })
					}, 1000)
				}
			}).catch((err: any) => {

				baseDataShow.codeText = err.msg
				baseDataShow.codeTextShow = true
			})

		} else {
			baseDataShow.codeTextShow = true

		}


	}
	const changeOrderCode = (e: any) => {
		takeGoodInfo.pickCode = e
		if (e.length >= 6) {
			baseDataShow.colorShow = true
		} else {
			baseDataShow.colorShow = false
			baseDataShow.codeTextShow = false


		}
	}


	// 转单
	const orderId = ref('')
	const isShow = ref(false)
	const clickConfirm = (remark: string) => {
		if (remark.trim() == '') {
			isShowFalse()
			proxy.$API(proxy).Toast('转单原因不能为空', 'error')
			return
		}

		tfOrder(remark)
		isShowFalse()
	}
	// 打开转单弹出框
	const clickIsShow = () => {
		console.log('orderObj.status', orderObj.status)
		if (orderObj.riderClientStatus == 1 && orderObj.status == 1) {
			isShow.value = true
		} else {
			// return 	proxy.$API(proxy).Toast('当前订单不可转单', 'error')
		}
	}
	// 关闭转单弹出框
	const isShowFalse = () => {
		isShow.value = false
	}

	const radiolist = ref([{
		name: '订单不顺路',
		disabled: false
	},
	{
		name: '暂时不能配送',
		disabled: false
	},
	{
		name: '距离当前位置较远',
		disabled: false
	},
	{
		name: '其他',
		disabled: false
	},
	])

	const tfOrder = (msg: any) => {
		let par = {
			orderId: orderId.value,
			msg: msg
		}

		$http.tfOrder(par, proxy).then(res => {
			proxy.$API(proxy).Toast('转单成功', 'success')
			setTimeout(() => {
				uni.navigateBack()
			}, 500)
		})
	}

	// 电话联系弹出层
	const phoneBtnList = ref([])
	const phoneListShow = ref(false)
	const getPhoneList = () => {
		// 如果订单未完成可以联系收货人取货人
		// 订单成功不能联系  直接隐藏
		let arr = []
		if (orderObj.riderDo == '1') {
			arr = [{
				title: '联系收件人',
				phone: orderObj.receivePhone,
				type: "C1"
			}, {
				title: '注册用户',
				phone: orderObj.userMobile,
				type: "C0"
			},]
		} else {
			arr = [
				{
					title: '联系发件人',
					phone: orderObj.pickPhone,
					type: "C1"
				},
				{
					title: '联系收件人',
					phone: orderObj.receivePhone,
					type: "C2"
				}, {
					title: '注册用户',
					phone: orderObj.userMobile,
					type: "C0"
				},
			]
		}

		if (orderObj.riderClientStatus == 4) {
			// return 	proxy.$API(proxy).Toast('订单已完成不能联系用户', 'error')
		}
		phoneBtnList.value = [...arr]
		phoneListShow.value = true
	}
	const btnCancel = () => {
		phoneListShow.value = false
	}

	return {
		Type,
		isShow,
		clickIsShow,
		orderId,
		radiolist,
		phoneListShow,
		getPhoneList,
		phoneBtnList,
		btnCancel,
		clickConfirm,
		isShowFalse,
		confirmChange,
		timeData,
		onChange,
		takeGoods,
		getDelatis,
		orderObj,
		makeOrder,
		defaultShow,
		butChange,
		callPhone,
		statusShowType,
		routeLine,
		covers,
		cancelSendCode,
		confirmSendCode,
		changeOrderCode,
		baseDataShow
	}
}
